import { KcpdShowDb } from "@/kcpd/moudle";
import { DisplaySlotId, world } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Game, GameComponent } from "@sapi-game/main";
import { HideAndSeekMainState } from "../mainState";
import { HideAndSeekRole } from "../player";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { Dimensions } from "@sapi-game/constants";

export class HideAndSeekDaemon extends GameComponent<HideAndSeekMainState> {
    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        if (!timer) return;
        KcpdShowDb.setDisplaySlot(DisplaySlotId.Sidebar);
        //更新剩余时间
        this.subscribe(timer.events.tick, (t) => {
            KcpdShowDb.clear();
            KcpdShowDb.setDisplaySlot(DisplaySlotId.Sidebar);
            KcpdShowDb.set(`§d剩余时间§r: ${t.remainingTime}`, 2);
            this.showLivePlayers();
        });
        //时间结束
        this.subscribe(timer.events.onTime, () => this.state.end(), {
            time: 0,
        });
        //tick
        this.subscribe(Game.events.interval, () => this.tick());
    }

    tick() {
        this.checkEnd();
        this.context.players.forEach((p) => {
            if (p.role == HideAndSeekRole.Seeker) {
                //给力量
                p.player.addEffect(EffectIds.Strength, 40, {
                    showParticles: false,
                    amplifier: 1,
                });
            }
            //设重生点
            p.player.setSpawnPoint({
                ...this.context.map.spawnPoint,
                dimension: Dimensions.Overworld,
            });
        });
    }

    checkEnd() {
        const allPlayers = this.context.players.getAll();
        const hasHider = allPlayers.some(
            (p) => p.alive && p.isValid && p.role == HideAndSeekRole.Hider
        );
        const hasSeeker = allPlayers.some(
            (p) => p.alive && p.isValid && p.role == HideAndSeekRole.Seeker
        );
        if (!hasHider || !hasSeeker) {
            this.state.end();
        }
    }

    /**存活玩家数显示 */
    showLivePlayers() {
        const livePlayers = this.context.players.filter((p) => p.alive);
        const hiderCnt = livePlayers.filter(
            (p) => p.role == HideAndSeekRole.Hider
        ).length;
        const seekerCnt = livePlayers.filter(
            (p) => p.role == HideAndSeekRole.Seeker
        ).length;
        KcpdShowDb.set(`§3躲藏者§r: ${hiderCnt}`, 1);
        KcpdShowDb.set(`§c追捕者§r: ${seekerCnt}`, 0);
    }
}
